import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { Row, Col, Card, Form, Input, Button, Divider, DatePicker, Badge, Select, Descriptions } from 'antd';
import StandardTable from 'components/StandardTable';
import SetCutIn from '../../components/UpLoadForm/setCutIn';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../DevLog/DevTask.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['等待设置', '设置中', '设置成功', '设置失败', '设置超时'];
const statusMap = ['default', 'processing', 'success', 'error'];
const setType = [
    '已绑定',
    '未绑定',
];
const SetForm = Form.create()(SetCutIn);

@connect(({ cutinlist, loading }) => ({
    cutinlist,
    loading: loading.models.cutinlist,
}))
@Form.create()
export default class CutInList extends PureComponent {
    state = {
        selectedRows: [],
        formValues: {},
        modalVisible: false,
    };

    componentDidMount() {
        const { dispatch } = this.props;
        let payload = {};
        dispatch({
            type: 'cutinlist/fetch',
            payload,
        });
        // dispatch({
        //     type: 'cutinlist/fetchCity',
        //     payload,
        // });

    }

    getFromValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;

            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }
            //console.log('postvalue', postvalue);
            if (postvalue.date && postvalue.date.length > 0) {
                const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
                const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
                postvalue = {
                    ...postvalue,
                    startSubDate,
                    endSubDate,
                };
                delete postvalue.date;
            }
        });
        return postvalue;
    };
    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = { ...obj };
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});
        const postvalue = this.getFromValue();
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'devtask/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
        });
        dispatch({
            type: 'cutinlist/fetch',
            payload: {},
        });
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'cutinlist/fetch',
            payload: postvalue,
        });
    };
    onExport = () => {
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'cutinlist/onExport',
            payload: postvalue,
            callback: src => {
                const link = document.createElement('a');
                link.download = 'filename';
                link.style.display = 'none';
                link.href = src;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
        });

    }
    onNew = () => {
        this.props.history.push(`/program/addcutintask`);
    }
    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        const { devName } = this.props.match.params;
        //const { cityCodes, playScreen } = this.props.playlist
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={5} sm={24}>
                        <FormItem>
                            {getFieldDecorator('date')(
                                <RangePicker
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                    // onChange={onChange}
                                    // onOk={onOk}
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('progName', {
                                rules: [{ required: false, message: '请输入节目名称!' }],
                            })(<Input placeholder="节目名称" />)}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('taskStatus')(
                                < Select allowClear="true" placeholder="运行状态" style={{ width: '100%' }}>
                                    <Option value={0}>未运行</Option>
                                    <Option value={1}>运行中</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>

                    <Col md={4} sm={24}>
                        <span className={styles.submitButtons}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={this.onNew} style={{ marginLeft: 20 }}>
                                新建任务
                            </Button>
                            <Button onClick={this.onExport} style={{ marginLeft: 20 }}>
                                导出
                            </Button>
                        </span>
                    </Col>

                </Row>
            </Form >
        );
    }

    setStart = (record) => {
        const { icTaskId } = record
        this.setState({ icTaskId, modalVisible: true })
    }

    render() {
        // //console.log('task', this.props.task);
        const { loading, cutinlist } = this.props;
        const { selectedRows } = this.state;
        const columns = [
            {
                title: '节目名称',
                dataIndex: 'progName',
            },
            {
                title: '类型',
                dataIndex: 'devUuid',
            },
            {
                title: '插播周期',
                dataIndex: 'icPlayPeriod',
            },
            {
                title: '插播范围',
                dataIndex: 'icScope',
            },
            {
                title: '发布模式',
                dataIndex: 'icMod',
            },
            {
                title: '城市',
                dataIndex: 'city',
            },
            {
                title: '运行状态',
                dataIndex: 'taskStatus',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
            },

            {
                title: '备注',
                dataIndex: 'remark',
            },

            {
                title: '操作',
                dataIndex: 'mdTelephone',
                render: (text, record, index) => (
                    <Fragment>

                        <a onClick={() => this.setStart(record)}>
                            启停
                        </a>
                        <Divider type="vertical" />
                        <Link
                            to={{
                                pathname: `/program/cutindetail/${record.icTaskId}`,
                                record,
                            }}
                        >
                            详情
                        </Link>
                    </Fragment>
                )
            },
        ];

        return (
            <PageHeaderLayout title="任务查询">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                        <StandardTable
                            rowKey="setId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={cutinlist}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <SetForm
                    handleModalVisible={this.handleModalVisible}
                    modalVisible={this.state.modalVisible}
                    icTaskId={this.state.icTaskId}
                    dispatch={this.props.dispatch}
                />

            </PageHeaderLayout>
        );
    }
}
